document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('search-input');
    const suggestionsContainer = document.getElementById('search-suggestions');
    let timeoutId = null;
    
    if (searchInput && suggestionsContainer) {
        // 输入事件处理
        searchInput.addEventListener('input', function(e) {
            const query = e.target.value.trim();
            if (query.length < 2) {
                hideSuggestions();
                return;
            }
            
            // 防抖处理
            clearTimeout(timeoutId);
            timeoutId = setTimeout(() => {
                fetchSuggestions(query);
            }, 300);
        });
        
        // 焦点事件处理
        searchInput.addEventListener('focus', function() {
            if (this.value.trim().length >= 2) {
                fetchSuggestions(this.value.trim());
            }
        });
        
        // 点击其他区域关闭建议框
        document.addEventListener('click', function(e) {
            if (!searchInput.contains(e.target) && !suggestionsContainer.contains(e.target)) {
                hideSuggestions();
            }
        });
    }
    
    // 获取搜索建议
    function fetchSuggestions(query) {
        const userId = 1; // 实际项目中应从会话获取
        
        fetch(`/api/suggestions?query=${encodeURIComponent(query)}&user_id=${userId}`)
            .then(response => response.json())
            .then(suggestions => {
                if (suggestions.length > 0) {
                    displaySuggestions(suggestions, query);
                } else {
                    hideSuggestions();
                }
            })
            .catch(error => {
                console.error('获取搜索建议失败:', error);
                hideSuggestions();
            });
    }
    
    // 显示搜索建议
    function displaySuggestions(suggestions, query) {
        suggestionsContainer.innerHTML = '';
        
        // 创建建议列表
        const ul = document.createElement('ul');
        ul.className = 'absolute z-50 w-full bg-white rounded-lg shadow-lg mt-1 overflow-hidden';
        
        suggestions.forEach(suggestion => {
            const li = document.createElement('li');
            
            // 根据建议类型添加不同样式
            let iconClass = 'fa-search';
            if (suggestion.type === 'history') {
                iconClass = 'fa-history';
            } else if (suggestion.type === 'product') {
                iconClass = 'fa-shopping-bag';
            } else if (suggestion.type === 'collaborative') {
                iconClass = 'fa-users';
            }
            
            // 高亮匹配的文本
            const highlightedText = suggestion.value.replace(
                new RegExp(query, 'gi'),
                match => `<span class="text-primary font-medium">${match}</span>`
            );
            
            li.className = 'px-4 py-2 hover:bg-neutral-100 cursor-pointer transition-colors flex items-center';
            li.innerHTML = `
                <i class="fa ${iconClass} text-neutral-400 mr-3"></i>
                <span>${highlightedText}</span>
            `;
            
            // 点击建议填充到搜索框
            li.addEventListener('click', function() {
                searchInput.value = suggestion.value;
                hideSuggestions();
                
                // 提交搜索
                const form = searchInput.closest('form');
                if (form) {
                    form.submit();
                }
            });
            
            ul.appendChild(li);
        });
        
        suggestionsContainer.appendChild(ul);
        suggestionsContainer.style.display = 'block';
    }
    
    // 隐藏搜索建议
    function hideSuggestions() {
        suggestionsContainer.style.display = 'none';
    }
});    